import axios, { AxiosError, type Method } from 'axios'
import { useUserStore } from '@/stores'
// 因为当前在.ts文件中，所以使用轻提示得用函数调用得方式
import { showToast } from 'vant'
import router from '@/router'
const baseURL = ''
const instance = axios.create({
  // 1. 基础地址，超时时间
  baseURL: 'https://consult-api.itheima.net/',
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    // TODO 2. 携带token
    const userStore = useUserStore()
    if (userStore.user?.token) {
      config.headers['Authorization'] = `Bearer ${userStore.user?.token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    // TODO 3. 处理业务失败
    if (res.data?.code !== 10000) {
      showToast(res.data?.message || '请求失败')
      return Promise.reject(res.data)
    }
    // TODO 4. 摘取核心响应数据
    return res.data
  },
  (err: AxiosError) => {
    // TODO 5. 处理401错误
    if (err.response?.status === 401) {
      const userStore = useUserStore()
      userStore.delUser()
      router.push({
        path: '/login',
        query: {
          returnUrl: router.currentRoute.value.fullPath
        }
      })
    }
    return Promise.reject(err)
  }
)
type Data<T> = {
  code: number
  message: string
  data: T
}
export const request = <T>(
  url: string,
  method: Method,
  submitData?: object
) => {
  return instance.request<any, Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}
export { baseURL, instance }
